import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_app/models/general_type.dart';
import 'package:flutter_app/pages/search/fliter_bar/data2.dart';
import 'package:flutter_app/scoped_model/filter_bar.dart';
import 'package:flutter_app/utils/common_picker.dart';
import 'package:flutter_app/utils/dio_http.dart';
import 'package:flutter_app/utils/scoped_model_helper.dart';

late String lastCityId = '';

class FilterBar extends StatefulWidget {
  const FilterBar({Key? key, required this.onChange}) : super(key: key);
  final ValueChanged onChange;
  @override
  _FilterBarState createState() => _FilterBarState();
}

class _FilterBarState extends State<FilterBar> {
  List<GeneralType> areaList = [];

  List<GeneralType> priceList = [];
  List<GeneralType> rentTypeList = [];
  List<GeneralType> roomTypeList = [];
  List<GeneralType> orientedList = [];
  List<GeneralType> floorList = [];

/* 4个筛选条件状态 */
  bool isAreaActive = false;
  bool isRentTypeActive = false;
  bool isPriceActive = false;
  bool isFilterActive = false;
/* 四个结果值 */
  String areaId = '';
  String rentTypeId = '';
  String priceId = '';
  List<String> filterIds = [];
/*
 */
  int areaValue = 0;
/* 四个私有方法 */
  _onChangeArea(context) {
    setState(() {
      isAreaActive = true;
    });
    var res = CommonPicker.showPicker(
        context: context,
        options: areaList.map((e) => e.name).toList(),
        value: areaValue);
    res.then((index) {
      if (index == null) return;
      setState(() {
        areaId = areaList[index].id;
      });
      _onChange();
    }).whenComplete(() {
      setState(() {
        isAreaActive = false;
      });
    });
  }

  _onChangeRentType(context) {
    setState(() {
      isRentTypeActive = true;
    });
    var res = CommonPicker.showPicker(
        context: context,
        options: rentTypeList.map((e) => e.name).toList(),
        value: areaValue);
    res.then((index) {
      if (index == null) return;
      setState(() {
        rentTypeId = rentTypeList[index].id;
      });
      _onChange();
    }).whenComplete(() {
      setState(() {
        isRentTypeActive = false;
      });
    });
  }

  _onChangePrice(context) {
    setState(() {
      isPriceActive = true;
    });
    var res = CommonPicker.showPicker(
        context: context,
        options: priceList.map((e) => e.name).toList(),
        value: areaValue);
    res.then((index) {
      if (index == null) return;
      setState(() {
        priceId = rentTypeList[index].id;
      });
      _onChange();
    }).whenComplete(() {
      setState(() {
        isPriceActive = false;
      });
    });
  }

  _onChangeFilter(context) {
    Scaffold.of(context).openEndDrawer();
  }

// 总的筛选方法
  _onChange() {
    var selectedIdList =
        ScopedHelperModel.getModel<FilterBarModel>(context).selectedIdList;
    widget.onChange(FilterBarResult(
        areaId: areaId,
        priceId: priceId,
        rentTypeId: rentTypeId,
        moreIds: selectedIdList.toList()));
  }

  _getData() async {
    var cityId = ScopedHelperModel.getAreaId(context);
    lastCityId = cityId;
    final url = '/houses/condition?id=$cityId';
    var res = await DioHttp.of(context).get(url);
    var data = json.decode(res.toString())["body"];

// 组件卸载调用setState报错解决
    if (!mounted) {
      return;
    }

    List<GeneralType> areaList = List<GeneralType>.from(data["area"]["children"]
        .map((item) => GeneralType.fromJson(item))
        .toList());
    // List<GeneralType> priceList = List<GeneralType>.from(data["price"]
    //         ["children"]
    //     .map((item) => GeneralType.fromJson(item))
    //     .toList());
    // List<GeneralType> rentTypeList = List<GeneralType>.from(data["rentType"]
    //         ["children"]
    //     .map((item) => GeneralType.fromJson(item))
    //     .toList());
    // List<GeneralType> roomTypeList = List<GeneralType>.from(data["roomType"]
    //         ["children"]
    //     .map((item) => GeneralType.fromJson(item))
    //     .toList());
    // List<GeneralType> orientedList = List<GeneralType>.from(data["oriented"]
    //         ["children"]
    //     .map((item) => GeneralType.fromJson(item))
    //     .toList());
    // List<GeneralType> floorList = List<GeneralType>.from(data["floor"]
    //         ["children"]
    //     .map((item) => GeneralType.fromJson(item))
    //     .toList());

    setState(() {
      this.areaList = areaList;
      // this.priceList = priceList;
      // this.rentTypeList = rentTypeList;
      // this.roomTypeList = roomTypeList;
      // this.orientedList = orientedList;
      // this.floorList = floorList;
    });
    Map<String, List<GeneralType>> dataList = <String, List<GeneralType>>{};
    dataList["roomTypeList"] = roomTypeList;
    dataList["orientedList"] = orientedList;
    dataList["floorList"] = floorList;

    ScopedHelperModel.getModel<FilterBarModel>(context).dataList = dataList;
  }

  @override
  void initState() {
    Timer.run(_getData);
    super.initState();
  }

  @override
  void didChangeDependencies() {
    _onChange();
    if (ScopedHelperModel.getAreaId(context) != lastCityId &&
        lastCityId.isNotEmpty) {
      _getData();
    }
    super.didChangeDependencies();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(10.0),
      decoration: const BoxDecoration(
          border: Border(
              bottom: BorderSide(
        color: Colors.black12,
      ))),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          FilterBarItem(
            name: '区域',
            onTab: _onChangeArea,
            isActive: isAreaActive,
          ),
          FilterBarItem(
            name: '方式',
            onTab: _onChangeRentType,
            isActive: isRentTypeActive,
          ),
          FilterBarItem(
            name: '租金',
            onTab: _onChangePrice,
            isActive: isPriceActive,
          ),
          FilterBarItem(
            name: '筛选',
            onTab: _onChangeFilter,
            isActive: isFilterActive,
          )
        ],
      ),
    );
  }
}

class FilterBarItem extends StatelessWidget {
  const FilterBarItem({
    Key? key,
    required this.name,
    required this.isActive,
    this.onTab,
  }) : super(key: key);
  final String name;
  final bool isActive;
  final Function(BuildContext)? onTab;
  @override
  Widget build(BuildContext context) {
    final activeColor = isActive ? Colors.green : Colors.black;

    return GestureDetector(
      onTap: () {
        onTab!(context);
      },
      child: Row(
        children: [
          Text(
            name,
            style: TextStyle(fontWeight: FontWeight.w800, color: activeColor),
          ),
          Icon(
            Icons.arrow_drop_down,
            color: activeColor,
          )
        ],
      ),
    );
  }
}
